<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

require APPPATH . '/libraries/ceklogin.php';

class Login extends CI_Controller {

    public function logout() {
        if ($this->session->userdata('log_in')) {
            $this->session->unset_userdata('log_in');
            $this->session->sess_destroy();
        }
        redirect(base_url() . 'login');
    }

    public function doLogin() {
        $nama_pengguna = mysql_real_escape_string($this->input->post('username'));
        $kata_sandi = mysql_real_escape_string($this->input->post('password'));
        $reqJson = $this->input->post('reqType');
        if ($reqJson == 'json') {
            $reqJson = true;
        } else {
            $reqJson = false;
        }
        $this->load->model(array('pengguna_model'));
        $coba_login = $this->pengguna_model->coba_login($nama_pengguna, $kata_sandi);
        if ($coba_login == 1) {
            $log_in = array(
                'username' => $nama_pengguna,
                'password' => $kata_sandi
            );
            $this->session->set_userdata(array('log_in' => $log_in));
            if ($reqJson) {
                echo json_encode(array('r' => 'ok', 'next' => base_url() . 'dashboard'));
            } else {
                echo "redirecting to dashboard";
                redirect(base_url() . 'dashboard');
            }
        } else {
            if ($reqJson) {
                echo json_encode(array('r' => 'no', 'reason' => '' . $coba_login));
            } else {
                redirect(base_url() . 'login');
            }
        }
    }

    public function index() {
        if ($this->session->userdata('log_in')) {
            redirect(base_url());
        } else {
            $this->load->view('login');
        }
    }

}

?>